package com.yao.mybatis.executor;

import com.yao.mybatis.config.Configuration;
import com.yao.mybatis.config.MappedStatement;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public abstract class BaseExecutor implements Executor {
    private Map<String, List<Object>> oneLevelCache = new HashMap<>();

    @Override
    public <E> List<E> query(MappedStatement mappedStatement, Configuration configuration, Object param) {
        //从缓存中获取
        String sql = mappedStatement.getSqlSource().getBoundSql(param).getSqlText();
        List<Object> objects = oneLevelCache.get(sql);
        // 一级缓存中存在就直接返回
        if (objects != null) {
            return (List<E>) objects;
        }
        //不存在就查询数据库
        List<Object> objects1 = queryFromDatabase(mappedStatement, configuration, param);
        oneLevelCache.put(sql,objects1);
        return (List<E>) objects1;
    }

    /**
     * 交给子类去实现，从数据库查询
     *
     * @param mappedStatement
     * @param configuration
     * @param param
     * @param <E>
     * @return
     */
    public abstract <E> List<E> queryFromDatabase(MappedStatement mappedStatement, Configuration configuration, Object param);
}
